#!/bin/bash

show_help() {
  echo -e "check libvirtd status"
  echo -e "Usage:"
  echo -e "$title check|clean|install [node]"
  echo -e "$title prickvm zabbix-stat|nvstat|sshd-nodns <vmuuid ... >"
  echo -e "Parameters:"
  echo -e "\tcheck          check libvirtd"
  echo -e "\tclean          check libvirtd and kill stuck vms"
  echo -e "\tnode           target node"
  echo -e "\n"
  echo -e "\tprickvm            do sth in vm by qemu-ga"
  echo -e "\t    test           run \"zabbix-stat; nvstat\" in vm"
  echo -e "\t    zabbix-stat    install zabbix-stat in vm"
  echo -e "\t    nvstat         install nvstat in vm"
  echo -e "\t    sshd-nodns     set UseDNS=no for sshd in vm"
}

cmdopts=$(getopt --longoptions title:,help \
                     --options +h -- "$@")

# set positional parameters
eval set -- "$cmdopts"

title=do_libvirt

while true; do
  case "$1" in
    --title )
        title="$2"
        shift 2;;
    -h | --help )
        show_help
        exit ;;
    -- ) shift; break ;;
    * ) break ;;
  esac
done

if [[ "$1" == "check" ]];then
    :
elif [ "$1" == "clean" ]; then
    :
elif [ "$1" == "install" ]; then
    :
elif [ "$1" == "prickvm" ]; then
    shift
    action=$1
    [ -n "$action" ] || { show_help >&1; exit -1; }
    shift
    # others is vm list: uuid1 uuid2 ...
    for vmuuid in $*; do
      read host inst <<< $(nyyos osc server show $vmuuid -f value -c OS-EXT-SRV-ATTR:hypervisor_hostname -c OS-EXT-SRV-ATTR:instance_name)
      [ -n "$host" ] || { echo "error host" >&1; continue; }
      [ -n "$inst" ] || { echo "error vm" >&1; continue; }
      echo "[INFO]$inst on $host uuid: $vmuuid"
      sudo ssh -t -o "StrictHostKeyChecking no" -o "BatchMode yes" root@$host docker exec -uroot nova_libvirt /prickvm $inst $action
      ret=$?
      if [ $ret -eq 0 ]; then
          echo "[INFO] prickvm $action $vmuuid done"
      else
          echo "[ERROR] prickvm $action $vmuuid failed $ret"
      fi
    done
    exit $?
else
    show_help >&1
    exit -1
fi
action=$1
shift

sudo ssh -t root@$controller /bin/bash /usr/local/bin/check_libvirt.sh $action $*

